package com.atguigu.aspect;

import com.atguigu.annotations.MyRedisCache;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;

import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

@Aspect
@Component
@Slf4j
public class MyRedisCacheAspect {

    @Autowired
    private RedisTemplate redisTemplate;
    /*@Pointcut("@annotation(com.atguigu.annotations.MyRedisCache)")
    public void point(){}
    @Around("point()")*/
    @Around("@annotation(com.atguigu.annotations.MyRedisCache)")
    public Object docache(ProceedingJoinPoint joinPoint){
        Object result =null;
        try {
            //1获得重载后的方法名
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            //2看获取的方法上有无注解myrediscache
            MyRedisCache annotation = method.getAnnotation(MyRedisCache.class);
            //boolean b = method.isAnnotationPresent(MyRedisCache.class);
            //3拿到了MyRedisCache这个注解标签，获得该注解上面配置的参数进行封装和调用
            String keyPrefix = annotation.keyPrefix();
            String matchValue = annotation.matchValue();
            //4 SpringEL 解析器
            SpelExpressionParser parser = new SpelExpressionParser();
            Expression expression = parser.parseExpression(matchValue);
            StandardEvaluationContext context = new StandardEvaluationContext();
            //5 使用反射获得方法里面的形参信息
            Object[] args = joinPoint.getArgs();//获取参数列表
            Parameter[] parameters = method.getParameters();
            for (int i = 0; i < parameters.length; i++) {
                System.out.println("获取方法的参数名和值:"+parameters[i].getName()+"\t"+args[i].toString());
                context.setVariable(parameters[i].getName(),args[i].toString());
            }
            //6 通过上述，拼接redis的最终key形式
            String key = keyPrefix+":"+expression.getValue(context).toString();
            System.out.println("---------------拼接redis的key的形式"+key);
            //7 先去redis里面查询看有没有
            result = redisTemplate.opsForValue().get(key);
            if (result!=null){
                System.out.println("-------------redis里面有,直接返回结果不打扰mysql"+result);
                return result;
            }
            //8 redis里面没有，去找msyql查询或叫进行后续业务逻辑
            //-------aop部分,才去找getUserById方法干活
            //主业务逻辑查询mysql,放行放行放行userMapper.selectById(id);
            result= joinPoint.proceed();
            //9 mysql步骤结束，还需要把结果存入redis一次，缓存补偿
            if (result!=null){
                System.out.println("------------redis里面没有,还要把结果存入redis,缓存补偿"+result);
                redisTemplate.opsForValue().set(key,result);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return result;
    }

}
